import java.util.*;

/**
 * @author LKQ
 * @date 2022/3/9 13:55
 * @description 用hashmap
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        String[] word1 = {"amazon","apple","facebook","google","leetcode"},
                word2 = {"ec","oc","ceoo"};
        solution.wordSubsets(word1,word2);
    }
    public List<String> wordSubsets(String[] words1, String[] words2) {
        Map<Character, Integer> m2 = new HashMap<>();
        for (String word: words2) {
            // 预处理word2
            int[] cnt = new int[26];
            for (char ch: word.toCharArray()) {
                cnt[ch-'a']++;
                if (m2.containsKey(ch)) {
                    int max = Math.max(cnt[ch-'a'], m2.get(ch));
                    m2.put(ch, max);
                }else {
                    m2.put(ch, cnt[ch-'a']);
                }
            }
        }
        List<String> ans = new ArrayList<>();
        for (String word: words1) {
            // 每个单词中字母的数量
            Map<Character, Integer> map = new HashMap<>();
            for (char ch: word.toCharArray()) {
                map.put(ch, map.getOrDefault(ch, 0) + 1);
            }
            boolean fit = true;
            for (Character ch: m2.keySet()) {
                if (map.getOrDefault(ch, 0) < m2.get(ch)) {
                    fit = false;
                    break;
                }
            }
            if (fit) {
                ans.add(word);
            }
        }
        return ans;
    }
}
